﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.SelectFileLibrary;
using System.Collections.Generic;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support;
using System.Web.UI.WebControls;
using System.Linq;
using System.Text;
using MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls;

namespace MS.InformationManagement.Controls.Layouts.MS.InformationManagement.Controls
{
    public partial class SelectFileLibrary : BaseApplicationPage, ISelectFileLibraryView
    {

        #region fields

        SelectFileLibraryPresenter _presenter;

        #endregion

        #region Properties

        //public List<FileEntity> Files 
        //{
        //    get { return Cache["SelectedFiles" + Page.Request.QueryString["isMainDocument"]] as List<FileEntity>; }
        //    set { Cache["SelectedFiles"  +Page.Request.QueryString["isMainDocument"]] = value; }
        //}

        public string ParentControlId { get { return Page.Request["ParentId"]; } }

        public List<FileEntity> ParentFiles
        {
            get { return Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "files"] as List<FileEntity>; }
            set { Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "files"] = value; }
        }

        public List<FileEntity> Files 
        {
            get { return Cache[ParentControlId+SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "Selectedfiles"] as List<FileEntity>; }
            set { Cache[ParentControlId+SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "Selectedfiles"] = value; }
        }

        public List<FileEntity> AllFiles
        {
            get
            {
                if (Cache[ParentControlId+SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "Allfiles"] == null)
                    Cache[ParentControlId+SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "Allfiles"] = new List<FileEntity>();
                return Cache[ParentControlId+SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "Allfiles"] as List<FileEntity>;
            }
        }


        public int isMainDocument
        {
            get
            {
                if (string.IsNullOrEmpty(Page.Request.QueryString["isMainDocument"]))
                    return 0;
                else
                    return int.Parse(Page.Request.QueryString["isMainDocument"]);
            }
        }

        public int PageIndex
        {
            get
            {
                return pgrTemplates.PageIndex;
            }
            set
            {
                pgrTemplates.PageIndex = value;
            }
        }

        public int PageSize
        {
            get
            {
                return pgrTemplates.PageSize;
            }
            set
            {
                pgrTemplates.PageSize = value;
            }
        }

        public int TotalRecords
        {
            get
            {
                return pgrTemplates.TotalRecords;
            }
            set
            {
                pgrTemplates.TotalRecords = value;
            }
        }

        #endregion

        #region Form Events

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (IsPostBack) return;
                _presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                this.HandleError(ex);
            }
        }

        protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType != DataControlRowType.DataRow) return;

                HyperLink fileViewer = e.Row.FindControl("lnkShowFile") as HyperLink;
                FileEntity currentEntity = e.Row.DataItem as FileEntity;
                fileViewer.NavigateUrl = string.Format("/sites/docs/_layouts/MS.InformationManagement.Controls/FileViewer.aspx?ParentControlId={0}&FileName={1}", ParentControlId, currentEntity.FileName);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                getSelectedFiles();
                this.CloseWindow();
            }
            catch (Exception ex)
            {
                this.HandleError(ex);
            }
           
        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            this.CloseWindow();
        }

        protected void chkArchivo_CheckedChanged(object sender, EventArgs e)
        {
            int numCheck = 0;
            int numSelect = Convert.ToInt16(Request.QueryString["numSelect"]);
            if (numSelect == 1)
            {
                foreach (GridViewRow item in gvFiles.Rows)
                {
                    if (numCheck > 1)
                        break;
                    if (item.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
                    {
                        if (((CheckBox)item.FindControl("chkArchivo")).Checked)
                            numCheck++;
                    }
                }
                if (numCheck > 1)
                {
                    HandleWarning("Por favor seleccionar solo un archivo de oficio remisorio");
                    btnAdd.Enabled = false;
                }
                else
                    btnAdd.Enabled = true;
            }

        }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _presenter = new SelectFileLibraryPresenter(this);
            pgrTemplates.OnPageChanged += new Pager.PageChangeHandler(pgrTemplates_OnPageChanged);
            //pgrTemplates.NextLinkText = ">>";
            //pgrTemplates.PreviousLinkText = "<<";
            pgrTemplates.NumberOfPagesToDisplay = 10;
            PageIndex = 0;
            PageSize = 10;

            //Clearing cache
            if(!IsPostBack)
                Cache.Remove(ParentControlId + SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "Allfiles");

        }

        #endregion

        #region Implemented Methods

        public void Show()
        {
            try
            {
                if (Convert.ToBoolean(isMainDocument) == true)
                    this.Files = this.Files.Where(x => x.FileName.Split('.')[1].Contains("docx") == true).ToList();

                SetGridView();

                PageIndex = 0;
                pgrTemplates.BuildPager();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void SetGridView()
        {
            gvFiles.DataSource = this.Files;
            gvFiles.DataBind();
        }

        void pgrTemplates_OnPageChanged(object sender, PageChangeEventArgs e)
        {
            _presenter.SearchDocuments();
            if (Convert.ToBoolean(isMainDocument) == true)
                this.Files = this.Files.Where(x => x.FileName.Split('.')[1].Contains("docx") == true).ToList();

            SetGridView();
            pgrTemplates.BuildPager();
        }

        #endregion

        #region Private Methods

        private void getSelectedFiles()
        {
            List<FileEntity> selected = new List<FileEntity>();
            bool _isMainDocument = Convert.ToBoolean(isMainDocument);

            foreach (GridViewRow row in gvFiles.Rows)
            {
                if (row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
                {
                    int selectedid = int.Parse(((Label)row.Cells[0].FindControl("lblId")).Text);
                    CheckBox chk = (CheckBox)row.Cells[1].FindControl("chkArchivo");
                    if (chk.Checked == true)
                    {
                        var fileName = (from currentFile in ParentFiles
                                        where currentFile.ItemId == selectedid
                                        select currentFile).FirstOrDefault();
                        if (fileName != null)
                            throw new Exception("Archivo ya existe");
                        else 
                        {
                            var selectedFile = (from file in Files
                                                where file.ItemId == selectedid
                                                select file).FirstOrDefault();
                            
                            if (selectedFile != null)
                                selectedFile.IsMainDocument = _isMainDocument;

                            if( _isMainDocument)
                                AllFiles.RemoveAll(x => x.IsMainDocument.Equals(_isMainDocument));

                            AllFiles.Add(selectedFile);
                        }
                    }
                }
            }


            if (ParentFiles == null)
                ParentFiles = new List<FileEntity>();

            /*if (_isMainDocument)
            {
                ParentFiles = AllFiles;
            }
            else
            {*/
                if (ParentFiles.Count == 0)
                    ParentFiles = AllFiles;
                else
                {
                    var newFiles = from file in AllFiles
                                   from parFile in ParentFiles
                                   where file.FileName != parFile.FileName
                                   select file;
                    ParentFiles = ParentFiles.Union(newFiles).ToList();
                }
           // }

            //Cache["SelectedFiles" + isMainDocument ] = selected;
        }

        #endregion

    }
}
